#!/bin/bash
# * =====================================================
# * Copyright © hk. 2022-2025. All rights reserved.
# * File name  : net-tftp.sh
# * Author     : 苏木
# * Date       : 2025-10-23
# * Version    : 
# * Description: 
# * ======================================================
##

# 脚本和工程路径
# ========================================================
SCRIPT_NAME=${0#*/}
SCRIPT_CURRENT_PATH=${0%/*}
SCRIPT_ABSOLUTE_PATH=`cd $(dirname ${0}); pwd`
PROJECT_ROOT=${SCRIPT_ABSOLUTE_PATH}/.. # 工程的源码目录，一定要和编译脚本是同一个目录

source "$PROJECT_ROOT/common/common.sh"

# ========================================================
# 功能实现
# ========================================================
EXECUTE_MODE=manu
function usage()
{
	prt "================================================="
    prt "${PINK}./${SCRIPT_NAME}      : 根据菜单选择功能${CLS}"
    prt "${PINK}./${SCRIPT_NAME} -h   : 显示打印信息用法后显示菜单${CLS}"
    prt "${PINK}./${SCRIPT_NAME} -a   : 自动执行所有步骤${CLS}"
    prt "================================================="
}
# 脚本运行参数处理
notice "There are $# parameters: $@ (\$1~\$$#)"
while getopts "ahp:" arg #选项后面的冒号表示该选项需要参数
    do
        case ${arg} in
            a) EXECUTE_MODE="auto" ;;
            h)
                log_echo_demo
                ;;
            p)
                if [ $OPTARG == "1" ];then
                    message "OPTARG=$OPTARG"
                fi
                ;;
            ?)  #当有不认识的选项的时候arg为?
                error "unkonw argument..."
                exit 1
                ;;
        esac
    done

# 功能函数实现
# ========================================================
# 检查包安装状态函数
function check_install() 
{
    if dpkg-query -W -f='${Status}' "$1" 2>/dev/null | grep -q "ok installed"; then
        return 0
    else
        return 1
    fi
}

# xinetd 作为扩展型网络守护进程，用于监听并管理多个服务的请求（如TFTP），按需启动服务进程以提高资源利用率
# 传统TFTP服务（如tftp-server或tftpd-hpa）通常将自身注册到xinetd下，通过其配置文件（如/etc/xinetd.d/tftp）控制服务启停及参数,
# 但是一些高版本的可能支持直接以独立进程运行，这里还是安装一下吧
function xinetd_install()
{
    local package=xinetd
    # 客户端检测
    if ! check_install ${package}; then
        warning "未检测到${package},即将开始安装"
        execute apt-get update -qq
        execute apt-get install -y ${package}
    fi
    # 再次检测
    if check_install ${package}; then
        success "${package}已安装,版本如下:"
        # dpkg -l | grep -E "tftp-hpa"
        dpkg -s ${package} | awk -F: '$0 ~ "Version"'
    else
        error "${package}不存在!"
    fi
}

function tftp_client()
{
    local tftp_package=tftp-hpa
    # 客户端检测
    if ! check_install ${tftp_package}; then
        warning "未检测到TFTP客户端,即将开始安装"
        execute apt-get update -qq
        execute apt-get install -y ${tftp_package}
    fi
    # 再次检测
    if check_install ${tftp_package}; then
        success "TFTP客户端${tftp_package}已安装,版本如下:"
        # dpkg -l | grep -E "tftp-hpa"
        dpkg -s ${tftp_package} | awk -F: '$0 ~ "Version"'
    else
        error "TFTP客户端不存在!"
    fi
}

function tftp_server()
{
    local tftp_package=tftpd-hpa
    # 客户端检测
    if ! check_install ${tftp_package}; then
        warning "未检测到TFTP服务端,即将开始安装"
        execute apt-get update -qq
        execute apt-get install -y ${tftp_package}
    fi
    # 再次检测
    if check_install ${tftp_package}; then
        success "TFTP服务端${tftp_package}已安装,版本如下:"
        # dpkg -l | grep -E "tftp-hpa"
        dpkg -s ${tftp_package} | awk -F: '$0 ~ "Version"'
    else
        error "TFTP服务端不存在!"
    fi
}

# tftp配置
function tftp_config()
{
    cdi ${SCRIPT_ABSOLUTE_PATH}/etc
    prt "${PINK}current path         :$(pwd)${CLS}"

    # xinetd配置文件：/etc/xinetd.conf 
    ls
    if [ ! -e "xinetd.conf" ];then
        error "xinetd.conf 不存在!"
        cdo
        return 1
    fi
    execute cp -af xinetd.conf /etc/xinetd.conf
    # tftp服务端在xinetd配置信息文件：/etc/xinetd.d/tftp
    if [ ! -e "xinetd.d/tftp" ];then
        error "xinetd.d/tftp 不存在!!!"
        cdo
        return 1
    fi

    if [ ! -d "/etc/xinetd.d" ];then
        warning "/etc/xinetd.d 不存在, 即将创建..."
        execute mkdir -p /etc/xinetd.d
    fi
    execute cp -af xinetd.d/tftp /etc/xinetd.d/tftp

    # tftp服务端配置文件：/etc/default/tftpd-hpa
    if [ ! -e "default/tftpd-hpa" ];then
        error "default/tftpd-hpa 不存在!!!"
        return 1
    fi
    if [ ! -d "/etc/default" ];then
        warning "/etc/default 不存在, 即将创建..."
        execute mkdir -p /etc/default
    fi
    execute cp -a default/tftpd-hpa /etc/default/tftpd-hpa

    # 创建tftp相关目录
    if [ ! -d "${TFTP_DIR}" ];then
        mkdir -pv ${TFTP_DIR}
        chmod 777 ${TFTP_DIR}
    fi

    # 重启相关服务
    info "重启相关服务..."
    execute service tftpd-hpa restart # 重启 tftpd-hpa
    execute service xinetd restart    # 重启 xinetd
    success "tftp配置完成"
    cdo
}

# tftp测试说明
function tftp_local_check()
{
	info "测试步骤如下:"
	prt "cd /home/sumu/3tftp   # 进入服务器工作目录"
	prt "touch test.txt        # 创建测试文件"
	prt "cd ~                  # 回到家目录"
	prt "tftp localhost        # tftp登录本机"
	prt "tftp> get test.txt    # tftp获取测试文件"
	prt "tftp> quit/q          # tftp退出"
	prt "ls                    # 查看是否获取成功"
}

# 自动执行所有步骤
function auto_setup() 
{
    xinetd_install
    tftp_client
    tftp_server
    tftp_local_check
    success "所有步骤执行完成!"
}

# 菜单与主进程
# ========================================================
function show_menu()
{
    message "================================================="
	message "                script by @苏木    ${CLS}"
	message "================================================="
    prt "${PINK}current path         :$(pwd)${CLS}"
    prt "${PINK}PROJECT_ROOT         :${PROJECT_ROOT}${CLS}"
    prt "${PINK}SCRIPT_ABSOLUTE_PATH :${SCRIPT_ABSOLUTE_PATH}${CLS}"
    echo ""
    prt "* [0] 安装xinetd"
    prt "* [1] 安装tftp客户端"
    prt "* [2] 安装tftp服务端"
    prt "* [4] 配置tftp服务"
    prt "* [5] 本地主机测试方案"
    echo "================================================="
}

# 主逻辑
function main() 
{
    if [ "$EXECUTE_MODE" = "manu" ]; then
        while true; do
            show_menu
            read -p "请选择操作 (0-5): " choice
            case "${choice}" in
                "0") xinetd_install;;
                "1") tftp_client;;
                "2") tftp_server;;
                "4") tftp_config;;
                "5") tftp_local_check;;
                *) error "无效选项!!!" ;;
            esac
            read -p "按回车继续..."
        done
    else
        info "正在自动执行所有配置步骤..."
        auto_setup
    fi
}

# 执行入口
# show_menu # 菜单显示
main "$@" # 主逻辑执行
